<?php

namespace App\Kuafu\WaiMai\Command;

use App\Kuafu\WaiMai\Channel\BaseWaiMai;
use App\Kuafu\WaiMai\Enum\WaiMaiDBEnum;
use App\Kuafu\WaiMai\Model\WaiMaiOrderModel;
use App\Kuafu\WaiMai\Model\WaiMaiSecureCardModel;
use App\Kuafu\WaiMai\Model\WaiMaiShopMappingModel;
use App\Kuafu\WaiMai\Service\BaseWaiMaiOrderService;
use App\Kuafu\WaiMai\Service\WaiMaiSecureCardService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class WaiMaiCacheSecureCard extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'waimai:cache-secure-card {shopId?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '外卖 - 缓存安心卡信息';

    /**
     * Create a new command instance.
     *
     * @return void//
     */
    public function __construct()
    {
        parent::__construct();
    }

    private static $myE;

    /**
     * Execute the console command
     *
     * @return
     */
    public function handle()
    {
        $argShopId = (int)$this->argument('shopId');

        $currentHour = (int)date('H');
        if ($currentHour < 10|| $currentHour > 22) {
            return;
        }

        // 所有店铺轮询
        WaiMaiShopMappingModel::query()
                              ->when($argShopId, function ($query) use ($argShopId) {
                                  $query->where('shopId', $argShopId);
                              })
                              ->where('sourceType', WaiMaiDBEnum::SOURCE_TYPE_MT_WM)
                              ->select(['sourceType', 'shopId', 'thirdShopId'])
                              ->get()
                              ->each(function ($item) {

                                  try {
                                      $fetch = (new WaiMaiSecureCardService($item->shopId))->fetchByApi();
                                      dump("shopId: {$item->shopId} fetch: {$fetch}");
                                      unset($fetch);
                                  } catch (\Exception $e) {
                                      Log::channel('waiMai')->error($e);
                                      self::$myE = $e;
                                  }
                              });

        if (self::$myE) {
            throw self::$myE;
        }

        $this->output->success("WaiMaiCacheSecureCard success...");
    }
}
